<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备类型" prop="types">
        <el-select
          v-model="queryParams.types"
          placeholder="设备类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.charge_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号" prop="number">
        <el-autocomplete
          v-model="queryParams.number"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入设备编号"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="安装时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="状态"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in dict.type.charge_pile_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargePileList" @selection-change="handleSelectionChange">
      <el-table-column label="设备编号" align="center" prop="number" />
      <el-table-column label="设备类型" align="center" prop="types">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.charge_type" :value="scope.row.types"/>
        </template>
      </el-table-column>
      <el-table-column label="安装时间" align="center" prop="installDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.installDate) }}</span>
        </template>
        </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.charge_pile_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleInfo(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            class="text-danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备编号" prop="number">
          <el-input :disabled="disabled" v-model="form.number" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备类型" prop="types">
          <el-select
            :disabled="disabled"
            v-model="form.types"
            placeholder="请选择设备类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.charge_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安装时间" prop="installDate">
          <el-date-picker
            :disabled="disabled"
            v-model="form.installDate"
            type="datetime"
            placeholder="选择安装时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="制造商" prop="manufacturer">
          <el-input :disabled="disabled" v-model="form.manufacturer" placeholder="请输入制造商" />
        </el-form-item>
        <el-form-item label="功率" prop="power">
          <el-input-number :disabled="disabled" v-model="form.power" :min="0" :precision="2"></el-input-number>
          <span style="margin-left: 10px">kW</span>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input :disabled="disabled" type="textarea" v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="所在位置" prop="postion">
          <div id="mapPoint" style="width: 600px; height: 250px"></div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="disabled" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listChargePile,
    listChargeRecordsPileNumber,
    getChargePile,
    addChargePile,
    updateChargePile,
    delChargePile,
    checkIsDel,
  } from "@/api/chargepile/chargePileManage";
  import AMapLoader from '@amap/amap-jsapi-loader'
  window._AMapSecurityConfig = {
    securityJsCode: '7b436841291cbd1488749eb10f1838a8' // '「申请的安全密钥」',
  }

  export default {
    name: "ChargePileManage",
    dicts: ['charge_type', 'charge_pile_status'],
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 岗位表格数据
        chargePileList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          beginTime: null,
          endTime: null,
          deviceType: null,
          deviceNumber: null,
          onlineStatus: null
        },
        queryNumber: [],
        // 日期范围
        dateRange: [],
        // 表单参数
        form: {},
        // 表单禁用
        disabled: false,
        // 表单校验
        rules: {
          types: [
            { required: true, message: "设备类型不能为空", trigger: "blur" }
          ],
          number: [
            { required: true, message: "设备编号不能为空", trigger: "blur" }
          ],
          power: [
            { required: true, message: "功率不能为空", trigger: "blur" },
            {
              pattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/,
              message: "请输入正确的默认金额",
              trigger: "blur"
            }
          ],
          manufacturer: [
            { required: true, message: "制造商不能为空", trigger: "blur" }
          ],
          postion: [
            { required: true, message: "安装位置不能为空", trigger: "blur" }
          ],
          installDate: [
            { required: true, message: "安装时间不能为空", trigger: "blur" }
          ],
        },

        // 地图
        adress: '', // 根据位置查找经纬度
        map: null,
        auto: null,
        geocoders: null,
        markers: [], // 标记点 数组
        lnglat: [], // 当前位置的经纬度
        mapForm: {
          showIndoorMap: true,
          resizeEnable: true,
          zoomEnable: true, // 地图是否可缩放，默认值为true
          dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
          doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
          zoom: 9, // 初始化地图级别
          center: [112.29, 30.98], // 初始化中心 湖北中心
          placeSearch: null, // 搜索关键字
          rotateEnable: true, // 地图是否可旋转
          features: ['bg', 'point', 'road','building'], // 设置地图上显示的元素种类
          layers: [],//使用多个图层
        }
      };
    },
    created() {
      this.getList();
      this.listChargeRecordsPileNumber();
    },
    methods: {
      // 设备编号查询自动补全
      querySearchAsync(queryString, cb) {
        var number = this.queryNumber;
        var results = queryString ? number.filter(this.createStateFilter(queryString)) : number;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      // 初始化地图
      initAMap() {
        if(this.form.postion !== undefined){
          this.mapForm.center[0] = Number(this.form.postion.split(";")[0])
          this.mapForm.center[1] = Number(this.form.postion.split(";")[1])
        }else{
          this.form.postion = this.mapForm.center[0] + ";" + this.mapForm.center[1];
          this.lnglat[0] = this.mapForm.center[0];
          this.lnglat[1] = this.mapForm.center[1];
        }
        AMapLoader.load({
          key: 'a033993f527d61fc06ac8adefd6c3b2c', // 申请好的Web端开发者Key，首次调用 load 时必填
          version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
          plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.ControlBar', 'AMap.Geocoder', 'AMap.Marker',
            'AMap.CitySearch', 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.InfoWindow', 'AMap.PlaceSearch'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap) => {
          // 设置标准图层
          let tileLayer = new AMap.TileLayer(); //高德默认标准图层
          this.mapForm.layers.push(tileLayer)

          // 获取到作为地图容器的DOM元素，创建地图实例
          this.map = new AMap.Map('mapPoint', // 设置地图容器id
            this.mapForm
          )

          if(this.form.postion !== undefined){
            this.setMarker(this.mapForm.center)
          }

          // 地图标尺
          this.map.addControl(new AMap.Scale());

          // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
          this.map.addControl(new AMap.ToolBar());

          this.setMarker(this.mapForm.center)
          if(this.disabled !== true){
            this.map.on('click', this.clickMapHandler)
          }
        }).catch(e => {
          console.log("错误" + e)
        })
      },
      // 点击地图事件获取经纬度，并添加标记
      clickMapHandler(e) {
        this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()]
        this.setMarker(this.lnglat)
      },
      //  添加标记
      setMarker(arr) {
        // console.log('添加标记', arr) // arr=[经度,纬度]
        this.removeMarker()
        const marker = new AMap.Marker({
          position: arr
        })
        marker.setMap(this.map)
        this.markers.push(marker) // 在data中记录标记点
      },
      // 删除之前后的标记点
      removeMarker() {
        // 判断是否存被标记的点，有--->移除
        if (this.markers) {
          this.map.remove(this.markers)
        }
      },
      // 获取经纬度
      async geoCode(arr) {
        const _this = this
        // console.log('要查询的地点', _this.adress)
        _this.geocoders = await new AMap.Geocoder({
          city: '' // 默认：“全国”
        })
        _this.geocoders.getLocation(_this.adress, function (status, result) {
          if (status === 'complete' && result.geocodes.length) {
            const local = result.geocodes[0].location
            const arr = [local.lng, local.lat]
            _this.mapForm.center = arr
            // 初始化地图
            _this.initAMap()
          } else {
            // console.log('根据地址查询位置失败')
          }
        })
      },

      /** 查询列表 */
      getList() {
        this.loading = true;
        if(this.dateRange !== null){
          this.queryParams.beginTime = this.dateRange[0]
          this.queryParams.endTime = this.dateRange[1]
        }else{
          this.queryParams.beginTime = null;
          this.queryParams.endTime = null;
        }
        listChargePile(this.queryParams).then(response => {
          this.chargePileList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      listChargeRecordsPileNumber(){
        listChargeRecordsPileNumber().then(response => {
          this.queryNumber = response.data;
          console.log(this.queryNumber)
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.disabled = false;
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          types: undefined,
          number: undefined,
          status: "0",
          postion: undefined,
          installDate: undefined,
          manufacturer: undefined,
          power: undefined,
          remark: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = []
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.postId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.disabled = false;
        this.reset();
        this.open = true;
        this.title = "添加设备";
        this.mapForm.zoom = 9
        this.initAMap()
      },
      /** 查看按钮操作 */
      handleInfo(row){
        this.handleUpdate(row)
        this.title = "查看设备";
        this.disabled = true;
        this.mapForm.zoom = 18
        this.initAMap()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.disabled = false;
        this.reset();
        const chargePileId = row.id || this.ids
        getChargePile(chargePileId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备";
          this.mapForm.zoom = 18
          this.initAMap()
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        // console.log(this.lnglat)
        console.log(this.form.postion)
        if(this.lnglat.length !== 0){
          this.form.postion = this.lnglat[0] + ";" + this.lnglat[1]
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              updateChargePile(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addChargePile(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const chargePileIds = row.id || this.ids;
        if(row.status === "1"){
          this.$modal.msgError("此充电桩正在使用，无法删除");
          return;
        }else if(row.status === "2"){
          this.$modal.msgError("此充电桩正在维修，无法删除");
          return;
        }else{
          checkIsDel(chargePileIds).then(response => {
            if(response.code === 200){
              this.$modal.confirm('是否确认删除此设备？').then(function() {
                return delChargePile(chargePileIds);
              }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
              }).catch(() => {});
            }
          })
        }
      },
    }
  };
</script>
